/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import com.opensymphony.xwork2.ActionSupport;
import debug.Debugger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import pojo.User;

import service.IUserService;

/**
 *
 * @author administrator
 */
public class LoginAction extends ActionSupport {

    private String uni;
    private String password;
    private User user;
    private IUserService<User> userService;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUni() {
        return uni;
    }

    public void setUni(String uni) {
        this.uni = uni;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public IUserService<User> getUserService() {
        return userService;
    }

    public void setUserService(IUserService<User> userService) {
        this.userService = userService;
    }

    public String login() {
        // check user
        this.user = userService.getUser(uni, password);
        if (user == null) {
            // user not exist
            return "error";
        } else {
            // user exists, create a session if not already
            HttpServletRequest request = ServletActionContext.getRequest();
            HttpSession session = request.getSession(true);
            session.setAttribute("user", this.user);
            session.setAttribute("uni", this.uni);
            session.setAttribute("tab", "base");
            return "main";
        }
    }

    public String fetchSecurityQuestion() {
        Debugger.msg("uni: " + uni);
        this.user = userService.findUserByUni(uni);
        if (this.user != null && this.user.getSecurityquestion() != null) {
            return "securityquestion";
        } else {
            return "login";
        }
    }

    public String out() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute("user");
            session.removeAttribute("uni");
        }
        return "login";
    }
}
